package com.tubemostwanted.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tubemostwanted.entity.Category;
import com.tubemostwanted.entity.CategoryFeed;
import com.tubemostwanted.entity.Tube;
import com.tubemostwanted.model.CategoryModel;
import com.tubemostwanted.model.TubeModel;

public class CategoryController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8"); 
		try {
			String path = ((HttpServletRequest) request).getRequestURI();
			String[] splittedURI = path.split("/");
			int page = 1;
			String cateAlias = "";
			if (splittedURI.length == 3) {
				cateAlias = splittedURI[splittedURI.length - 1];

			} else if (splittedURI.length == 4) {
				cateAlias = splittedURI[splittedURI.length - 2];
				try {
					page = Integer
							.parseInt(splittedURI[splittedURI.length - 1]);
				} catch (Exception e) {
					page = 1;
				}
			} else {
				response.sendRedirect("/home");
			}
			cateAlias = URLDecoder.decode(cateAlias, "UTF8");
			System.out.println("Cate to search : " + cateAlias);
			Category cate = CategoryModel.getByCateAlias(cateAlias);
			if (cate != null) {
				List<Tube> listTube = TubeModel
						.getByCategory(cateAlias, page, 12);
				CategoryFeed result = new CategoryFeed();
				result.setCurrentPage(page);
				result.setListTube(listTube);
				result.setAlias(cateAlias);
				result.setTotalResult(cate.getCount());
				result.setTitle(cate.getTitle().getValue());
				request.setAttribute("url", request.getRequestURL());				
				request.setAttribute("result", result);								
				request.getRequestDispatcher("/category_show.jsp").forward(
						request, response);
			} else {
				System.out.println("Error path.");
				response.sendRedirect("/home");
			}
		} catch (Exception e) {
			System.out.println("Exception.");
			e.printStackTrace();
			response.sendRedirect("/home");
		}
	}
}
